<template>
  <el-form
    :rules="rules"
    :disabled="type == 'examine'"
    :model="formModel"
    :class="$style['form-container']"
    ref="dataRef"
  >
    <el-row :gutter="20" v-for="(group, index) in formItemsVisible" :key="index">
      <el-col
        v-for="(item, key) in group"
        :xl="columnsPerRow < 5 ? 24 / columnsPerRow : 6"
        :lg="columnsPerRow < 5 ? 24 / columnsPerRow : 6"
        :md="12"
        :sm="24"
        :key="item.key"
      >
        <el-form-item
          v-bind="item.props"
          :key="item.key"
          :prop="key"
          :rules="handleRule(item, key)"
        >
          <el-input
            v-if="item.type === 'input'"
            v-bind="item.elementProps"
            size="small"
            v-model="formModel[key]"
          />
          <el-input-number
            v-else-if="item.type === 'number'"
            size="small"
            v-bind="item.elementProps"
            v-model="formModel[key]"
          />
          <el-select
            v-else-if="item.type === 'select'"
            v-bind="item.elementProps"
            size="small"
            v-model="formModel[key]"
          >
            <el-option
              v-for="opt in item.options"
              :key="opt.value"
              :label="opt.label"
              :value="opt.value"
            >
            </el-option>
          </el-select>
          <SelectTree
            v-else-if="item.type === 'selectTree'"
            v-bind="item.elementProps"
            :inputValue="item.inputValue"
            :treeProps="item.treeProps"
            :treeData="item.treeData"
            v-model="formModel[key]"
          />
          <el-date-picker
            v-else-if="item.type === 'date'"
            size="small"
            :type="item.elementProps.type"
            v-bind="item.elementProps"
            v-model="formModel[key]"
            @change="
              (val) => {
                change(val, key)
              }
            "
          >
          </el-date-picker>
          <el-cascader
            v-else-if="item.type === 'cascader'"
            v-bind="item.elementProps"
            v-model="formModel[key]"
            size="small"
          ></el-cascader>
          <FileUpload
            v-else-if="item.type === 'file'"
            v-bind="item.elementProps"
            v-model="formModel[key]"
            :type="type"
          ></FileUpload>

          <CmpUpload
            v-else-if="item.type === 'upload'"
            :disabled="item.elementProps.disabled"
            :item="{
              key: key,
            }"
            v-model:form="formModel"
          />
          <!-- 选择人员 -->
          <SelectUser
            v-else-if="item.type === 'selectUser'"
            :disabled="item.elementProps.disabled"
            :item="{
              key: key,
            }"
            v-model:form="formModel"
          />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>
<script lang="ts">
import SelectTree from '@/components/SelectTree/index.vue'
import { useI18n } from 'vue-i18n'
import { defineComponent, PropType, onMounted, ref, inject, unref } from 'vue'
import { FormItemKey, ObjectType } from 'typings/interfaces'
import FileUpload from './components/FileUpload.vue'
import dayjs from 'dayjs'
import CmpUpload from '@/components/Form/Item/UploadV2.vue'
import SelectUser from '@/components/selectUser/index.vue'
import { hasIn } from 'lodash'
// import useValidate from '@/hooks/useValidate'
export default defineComponent({
  components: {
    SelectTree,
    FileUpload,
    CmpUpload,
    SelectUser,
  },
  props: {
    columnsPerRow: {
      type: Number,
      required: true,
      default: 1,
    },
    item: {
      type: Object,
      default: () => ({}),
    },
    type: {
      type: String,
      default: () => '',
    },
    formItems: {
      type: Object,
      required: true,
      default: () => ({}),
    },
    formModel: {
      type: Object,
      required: true,
      default: () => ({}),
    },
    rules: {
      type: Object as PropType<
        Record<
          FormItemKey,
          Array<{
            required: boolean
            message: string
            validator?: (...args: any) => any
            trigger?: 'blur' | 'change'
          }>
        >
      >,
      default: () => ({}),
    },
  },
  setup(props) {
    const formItemsVisible = ref<any>('')
    const dataRef = ref<ObjectType | null>(null)
    const addValidate = inject<any>('ValidateData')
    const change = (value: any, key) => {
      //  const form = unref(loginFormRef)
      //   try {
      //       form.validate((valid) => {
      //         console.log(valid)
      //       })
      //   } catch (err) {
      //     console.log(err)
      //   }
      props.formModel[key] = dayjs(value).format(props.formItems[key].elementProps.format)
    }
    const handleRule = (item: any, key: any) => {
      const { t } = useI18n()
      if (item.required) {
        return [
          {
            required: true,
            message: t('lang.validate.required'),
            validator: (rule, value, callback) => {
              if (
                item.type === 'number' &&
                hasIn(item.elementProps, 'min') &&
                value >= item.elementProps['min']
              ) {
                callback()
              }
              if (props.formModel[key] == '') {
                callback(new Error(t('lang.validate.required')))
              } else {
                callback()
              }
            },
          },
        ]
      }
    }
    onMounted(() => {
      formItemsData()
      const validate = () => dataRef.value?.validate()
      addValidate(validate)
    })

    const formItemsData = () => {
      let rst: Array<ObjectType> = []
      const columnsPerRow = props.columnsPerRow > 4 ? 4 : props.columnsPerRow
      let i = 0
      let temp: any = {}
      for (let key in props.formItems) {
        if (i % columnsPerRow === 0) {
          if (Object.keys(temp).length > 0) rst.push({ ...temp })
          temp = {}
        }
        if (!props.formItems[key].invisible) {
          temp[key] = props.formItems[key]
          i++
        }
      }
      if (Object.keys(temp).length > 0) rst.push({ ...temp })
      formItemsVisible.value = rst
    }
    return {
      dataRef,
      change,
      handleRule,
      formItemsVisible,
    }
  },
})
</script>
<style lang="scss" module>
.form-container {
  :global(.el-col) {
    margin: 5px 0;
  }

  :global(.el-input-number) {
    width: 100%;
  }

  :global(.el-date-editor) {
    width: 100% !important;
  }
}
</style>
